import { ref } from 'vue';
import useApi from './useApi';

function useApiPagination(api, config) {
  const initialPage = { pageNumber: 1, pageSize: 10 };

  const page = ref(initialPage);

  const req = useApi(api, {
    auto: true,
    initialData: { list: [], total: 0 },
    ...config,
    defaultParams: { ...initialPage, ...config.defaultParams },
    onPass(formated, params) {
      page.value = { pageNumber: params.pageNumber, pageSize: params.pageSize };
      config.onPass?.(formated, params);
    },
  });

  // 查询
  const search = (params) => {
    req.run({ ...params, pageNumber: 1 });
  };

  // 页面跳转
  const goto = (pageNumber, pageSize) => {
    req.run({ ...req.params.value, pageNumber, pageSize });
  };

  return {
    ...req,
    page,
    search,
    goto,
  };
}

export default useApiPagination;
